#'
#' Merge populations or communities into a single community
#' 
#' @aliases merge.population merge.community lmerge
#'
#' @param com1 the first community
#' @param com2 the second community
#' @param pop1 the first population
#' @param pop2 the second population
#' @param pops a list of populations
#'
#' @usage
#' merge(pop1, pop2)
#' merge(com1, com2)
#' lmerge(pops)
#'
#'
#' @note
#' please make sure that the plotdim of the two plots should be the same. 
#' Order of the individuals will change in the merge
#' 
#' @examples
#' set.seed(1)
#' 
#' splist=paste("sp",1:4,sep="")
#' abundance=sample(1:40,4)
#' plotdim=c(80,100)
#' com1=rcommunity(splist,abundance,plotdim)
#' com2=rcommunity(splist,abundance,plotdim)
#'
#' comall=merge(com1,com2)
#' 
#' 
#' pop1=rpopulation("sp1")
#' pop2=rpopulation("sp2")
#' 
#' merge(pop1,pop2)
#' 
#'
#' @export
lmerge=function(pops){
  x=numeric()
  y=numeric()
  species=c()
  S=length(pops)
  trait_names=get_trait_names(pops[[1]])
  trait=as.data.frame(matrix(nrow=0,ncol=length(trait_names)))
  colnames(trait)=trait_names
  
  for(i in 1:S){
    x=c(x,pops[[i]]$x)
    y=c(y,pops[[i]]$y)
    species=c(species,rep(attr(pops[[i]],"species"),total_abundance(pops[[i]])))
    if(length(trait_names)!=0)
      trait=rbind(trait,pops[[i]][trait_names])
  }
  if(length(trait_names)!=0){
    com=community(species=species,x = x,y=y, 
                  plotdim = attr(pops[[1]],"plotdim"),
                  traits=trait,valid_check = TRUE)
    
  }else{
    com=community(species=species,x = x,y=y, 
                  plotdim = attr(pops[[1]],"plotdim"),
                  valid_check = TRUE)
    
  }
  com$species=as.factor(as.character(com$species))
  return(com)
}

merge.population=function(pop1,pop2){
  #check the plotdim
  if(all(attr(pop1,"plotdim")!=attr(pop1,"plotdim")))
    stop("The plot ranges are different between the two populations")
  if(dim(pop1)[2] != dim(pop2)[2]) stop("Two different structured populations can not be merged")
  
  part=rbind(pop1,pop2)
  species=c(rep(attr(pop1,"species"),total_abundance(pop1)),rep(attr(pop2,"species"),total_abundance(pop2)))
  com=cbind(species=species,part)
  attr(com,"plotdim")=attr(pop1,"plotdim")
  class(com)=c("community",class(com))
  return(com)
}


merge.community=function(com1,com2){
  #check the plotdim
  if(all(attr(com1,"plotdim")!=attr(com1,"plotdim")))
    stop("The plot ranges are different between the two communities")
  if(dim(com1)[2] != dim(com2)[2]) stop("Two different structured communities can not be merged")
  
  com=rbind(com1,com2)
  com$species=as.factor(as.character(com$species))
  #TODO COMBINE THE TRAITS DATAFRAME
  return(com)
}